<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { navigateTo, switchTab } from '@uni-helper/uni-promises'
import { aliPayRegister, checkUsrAccount } from '@/api/user'
import user from '@/composables/user'
import { toast } from '@/utils/utils'
import globalVariable from '@/utils/globalVariable'
import type { RegisterFailDto } from '@/api/user/type'
import { PlatformEnum } from '@/constant/enum'

const statusBarHeight = ref(0)
const showModal = ref(false)

const formData = ref({
    userName: '',
    idCardNo: '',
    phone: '',
})

const disablePhone = ref(false)
const openId = ref('')
const errorMsg = ref('')

const platformName = computed(() => {
    return globalVariable.platForm === 'mp-alipay' ? '支付宝' : '微信'
})

/**
 * 处理支付宝注册
 *
 * @returns 注册结果
 */
async function handleAlipayRegister() {
    const res = await aliPayRegister({
        idCardNo: formData.value.idCardNo,
        phone: formData.value.phone,
        userName: formData.value.userName,
        alipayOpenId: openId.value,
        id: '',
        userId: '',
    })
    // 注册异常了
    if ((res as RegisterFailDto)?.code === 100) {
        showModal.value = true
        errorMsg.value = (res as RegisterFailDto)?.msg
    }
    else {
        await user.login()
        toast('注册成功，正在为您跳转...')

        if (globalVariable.backUrl) {
            console.log('basic-form', globalVariable.backUrl)
            navigateTo({ url: globalVariable.backUrl })
        }
        else {
            switchTab({
                url: '/pages/mine/mine',
            })
        }
    }
}

function getUserAccountInfo() {
    return new Promise(async (resolve, reject) => {
        const res = await checkUsrAccount({
            phone: formData.value.phone,
            idCardNo: formData.value.idCardNo,
            platform: PlatformEnum[globalVariable.platform as keyof typeof PlatformEnum],
            alipayOpenId: user.alipayOpenId.value,
            userName: formData.value.userName,
        }) as RegisterFailDto
        if (res.code === 100) {
            showModal.value = true
            errorMsg.value = (res as RegisterFailDto)?.msg
            reject(false)
        }
        else {
            resolve(true)
        }
    })
}

async function onSubmit() {
    if (!formData.value.userName.trim()) {
        toast('请输入您的姓名')
        return
    }
    if (!formData.value.idCardNo.trim() || formData.value.idCardNo.trim()?.length !== 18) {
        toast('请输入正确的身份证号码')
        return
    }
    if (!formData.value.phone.trim() || formData.value.phone.trim().length !== 11) {
        toast('请输入正确格式的手机号码')
        return
    }

    await getUserAccountInfo()

    // ifdef MP-ALIPAY
    handleAlipayRegister()
    // endif
}

onLoad((params) => {
    disablePhone.value = !!params?.phone
    formData.value.phone = params?.phone || ''
    openId.value = params?.openId || ''
})

onMounted(() => {
    statusBarHeight.value = uni.getWindowInfo().statusBarHeight
    // #ifdef MP-ALIPAY
    my.setNavigationBar({
        frontColor: '#ffffff',
        backgroundColor: '#ffffff',
    })
    // #endif
})
</script>

<template>
    <NavbarContainer
        background-url="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager363631e9-06ab-476d-890f-a9978e34dd83.png">
        <view class="">
            <view class="box-border px-40rpx">
                <img class="h-60rpx w-296rpx" src="../../static/images/basic-form/two-real.png" alt="">
                <view class="mb-20rpx mt-10rpx flex items-center text-white">
                    <img class="mr-5rpx h-38rpx w-38rpx" src="../../static/images/basic-form/real.png" alt="">
                    <text @click="showModal = true">实名信息认证</text>
                    <img class="h-38rpx w-38rpx" src="../../static/images/basic-form/split.png" alt="">
                    <img class="mr-5rpx h-38rpx w-38rpx" src="../../static/images/basic-form/card.png" alt="">
                    <text>领取薪资</text>
                </view>
                <view class="text-xs text-white text-op-70 lh-relaxed">
                    为确保薪资精准无误地发放至每位员工手中，并依照国家税法规定履行合法报税义务，平台需收集职工的真实身份信息及有效的手机号码。根据国家政策法规，保护自由职业者合法权益，所有数据都经过数据平台严格加密，保障您的信息安全。
                </view>
            </view>
            <view class="mt-20rpx box-border px-40rpx">
                <view class="flex rounded-lg bg-#FFF1EC p-25rpx text-base">
                    <img class="mr-8rpx h-36rpx w-36rpx flex-shrink-0 -mt-6rpx"
                         src="../../static/images/basic-form/info.png" alt="">
                    <view class="lh-normal">
                        <text class="text-gray">请确保</text>
                        <text class="font-bold">填写身份信息与{{ platformName }}实名一致</text>
                        <text class="text-orange font-bold underline">不要使用他人{{ platformName }}注册。</text>
                    </view>
                </view>
                <view class="mt-20rpx flex items-center justify-between rounded-lg bg-white p-30rpx">
                    <view>姓名</view>
                    <input v-model="formData.userName" class="flex-1 text-right text-base" placeholder="请输入您的真实姓名">
                </view>
                <view class="mt-20rpx flex items-center justify-between rounded-lg bg-white p-30rpx">
                    <view>身份证</view>
                    <input v-model="formData.idCardNo" class="flex-1 text-right text-base" placeholder="请输入您本人的身份证号码">
                </view>
                <view class="mt-20rpx flex items-center justify-between rounded-lg bg-white p-30rpx">
                    <view>手机号</view>
                    <input v-model="formData.phone" :disabled="disablePhone" class="flex-1 text-right text-base"
                           placeholder="请输入本人手机号方便联系">
                </view>
                <button class="mt-80rpx rounded-full border-none bg-orange text-white" @click="onSubmit">提交</button>
            </view>
            <RegisterFailDialog v-model:show="showModal" :id-card-no="formData.idCardNo" :user-name="formData.userName"
                                :error-msg="errorMsg" />
        </view>
    </NavbarContainer>
</template>

<style scoped>
.set-bg {
    background: url('https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager363631e9-06ab-476d-890f-a9978e34dd83.png') no-repeat;
}
</style>

<route lang="json">
{
    "style": {
        "navigationBarTitleText": "实名认证",
        "mp-alipay": {
            "transparentTitle": "always"
        }
    }
}
</route>
